package com.Lemon.Zhkuhealth.admin.controller;

import com.Lemon.Zhkuhealth.common.constant.MessageConstant;
import com.Lemon.Zhkuhealth.common.pojo.entity.ReserveSetting;
import com.Lemon.Zhkuhealth.common.util.PoiUtils;
import com.Lemon.Zhkuhealth.common.util.R;
import com.Lemon.Zhkuhealh.api.service.IReserveSettingService;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.time.LocalDate;
import java.util.List;

import jakarta.servlet.http.HttpServletResponse;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * Some description here.
 *
 * @author LanPingX.com
 * @version 1.0, 2023/08/30
 */
@RestController
@RequestMapping("/ordersetting")
public class ReserveSettingController {
    @DubboReference
    IReserveSettingService reserveSettingService;


    @RequestMapping("/upload")
    public R upload(@RequestParam("excelFile") MultipartFile excelFile) {
        try {
            List<String[]> list = PoiUtils.readExcel(excelFile);
            ArrayList<ReserveSetting> reserveSettings = new ArrayList<>();

            // *** 关键修改：更改日期格式化模式以匹配实际的日期字符串格式 'YYYY/MM/DD' ***
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd"); // 将 '-' 改为 '/'

            for (String[] strings : list) {
                String orderDateStr = strings[0]; // 例如 "2025/07/21"
                String number = strings[1];

                ReserveSetting reserveSetting = new ReserveSetting();

                LocalDate orderDate = LocalDate.parse(orderDateStr, formatter);
                reserveSetting.setOrderDate(orderDate);

                reserveSetting.setNumber(Integer.parseInt(number));
                reserveSettings.add(reserveSetting);
            }
            reserveSettingService.save(reserveSettings);
        } catch (Exception e) {
            e.printStackTrace();
            return new R(false, MessageConstant.IMPORT_ORDERSETTING_FAIL);
        }
        return new R(true, MessageConstant.IMPORT_ORDERSETTING_SUCCESS);
    }

    @RequestMapping("/getOrderSettingByMonth")
    public R getOrderSettingByMonth(String date) {
        try {
            List<ReserveSetting> orderSettings = reserveSettingService.listReserveSettingByMonth(date);
            return new R(true, MessageConstant.GET_ORDERSETTING_SUCCESS, orderSettings);
        } catch (Exception e) {
            e.printStackTrace();
            return new R(false, MessageConstant.GET_ORDERSETTING_FAIL);
        }
    }
    /**
     * 下载预约设置模板文件
     *
     * @param response HttpServletResponse 用于输出文件流
     */
    @GetMapping("/downloadTemplate") // 使用 @GetMapping 明确处理 GET 请求
    public void downloadTemplate(HttpServletResponse response) {
        String templateFileName = "ordersetting_template.xlsx"; // 模板文件名，需要与前端下载的文件名一致
        ClassPathResource classPathResource = new ClassPathResource("template/" + templateFileName); // 假设模板文件放在 resources/template/ 目录下

        try (InputStream inputStream = classPathResource.getInputStream();
             OutputStream outputStream = response.getOutputStream()) {

            // 设置响应头，告知浏览器这是一个文件下载
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); // Excel .xlsx 文件的 MIME 类型
            response.setHeader("Content-Disposition", "attachment; filename=" + templateFileName);
            response.setHeader("Content-Length", String.valueOf(classPathResource.contentLength()));

            // 将模板文件内容拷贝到响应输出流
            FileCopyUtils.copy(inputStream, outputStream);
            outputStream.flush(); // 确保所有数据都已发送
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @RequestMapping("/editReservations")
    public R editReservations(@RequestBody List<ReserveSetting> reserveSettings) {
        try {
            // Validate input if necessary (e.g., number should be non-negative)
            for (ReserveSetting setting : reserveSettings) {
                if (setting.getNumber() < setting.getReservations()) {
                    return new R(false, "可预约人数不能小于已预约人数！");
                }
                // Further validation like date format, future date, etc.
            }

            // Call the service layer to process the update/save operation
            reserveSettingService.updateOrSaveBatch(reserveSettings); // Assuming a batch update/save method

            return new R(true, "预约设置保存成功！");
        } catch (Exception e) {
            e.printStackTrace();
            return new R(false, "预约设置保存失败！");
        }
    }
}
